import React, { useRef, useState } from 'react'
import { PageContainer } from '@ant-design/pro-layout'
import ProTable from '@ant-design/pro-table'
import { Button, Avatar, Switch, message } from 'antd'
import { PlusOutlined, UserOutlined } from '@ant-design/icons'
import { getUsers, lockUser } from '@/services/user' 
import CreateOrEdit from './components/CreateOrEdit'


export default function Index() {

  const actionRef = useRef()

  const [isModalVisible, setIsModalVisible] = useState(false)
  const [editId, setEditId] = useState(undefined)

  // 获取用户列表数据
  const getData = async (params) => {
    const response = await getUsers(params)
    return {
      data: response.data,
      // success 请返回 true，不然 table 会停止解析数据，即使有数据
      success: true,
      // 不传会使用 data 的长度，如果是分页一定要传
      total: response.meta.pagination.total
    }
  }

  // 启用和禁用 用户
  const handleLockUser = async (uid) => {
    const response = await lockUser(uid)
    console.log(response.status === undefined)
    if(response.status === undefined) message.success('操作成功!')
  }

  // 控制模态框显示与隐藏
  const isShowModal = (show, uid = undefined) => {
    setIsModalVisible(show)
    setEditId(uid)
  }

  const columns = [
    {
      title: '头像',
      dataIndex: 'avatar_url',
      hideInSearch: true,
      render: (_, record) => <Avatar src={record.avatar_url} size={32} icon={<UserOutlined />} />
    },
    {
      title: '姓名',
      dataIndex: 'name'
    },
    {
      title: '邮箱',
      dataIndex: 'email'
    },
    {
      title: '是否禁用',
      dataIndex: 'is_locked',
      hideInSearch: true,
      render: (_, record) => <Switch 
        onChange={ async () => handleLockUser(record.id) }
        checkedChildren="启用" unCheckedChildren="禁用" 
        defaultChecked={record.is_locked === 0}
      />
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      hideInSearch: true
    },
    {
      title: '操作',
      render: (_, record) => <a onClick={() => isShowModal(true, record.id)}>编辑</a>
    }
  ]

  return (
    <PageContainer>
      {/* 高级表格 */}
      <ProTable
        columns={columns}
        actionRef={actionRef}
        // request={ async (params = {}, sort, filter) => getUsers(params) }
        request={ async (params = {}, sort, filter) => getData(params) }
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          pageSize: 5,
        }}
        dateFormatter="string"
        headerTitle="用户列表"
        toolBarRender={() => [
          <Button key="button" icon={<PlusOutlined />} type="primary" onClick={ () => isShowModal(true) }>
            新建
          </Button>
        ]}
      />
      {
        // 配合 hook 模拟声明周期函数 componentDidMount， 重写卸载和挂载、与 骨架屏 配合使用
        isModalVisible ? 
          <CreateOrEdit editId={editId} isModalVisible={isModalVisible} isShowModal={isShowModal} actionRef={actionRef} /> 
        : ''
      }
    </PageContainer>
  )
}
